//
//  UIImage+Filter.m
//  Mahjong
//
//  Created by 饶首建 on 17/7/5.
//  Copyright © 2017年 com.ikamobile.com. All rights reserved.
//

#import "UIImage+Filter.h"
#import <CoreGraphics/CoreGraphics.h>
#import <CoreImage/CoreImage.h>
#import <ImageIO/ImageIO.h>


@implementation UIImage (Filter)

- (UIImage *)addFilter:(NSString *)filterName{
    /* 滤镜类型
    [NSArray arrayWithObjects:@"original", @"ColorInvert", @"ColorMonochrome", @"ColorPosterize", @"FalseColor",@"RGBToneCurve", @"MaximumComponent", @"MinimumComponent", @"PhotoEffectChrome", @"PhotoEffectMono", @"PhotoEffectNoir",@"PhotoEffectProcess", @"PhotoEffectTonal", @"PhotoEffectTransfer", @"SepiaTone", nil];
     */
    //将UIImage转换成CIImage
    CIImage *ciImage = [[CIImage alloc] initWithImage:self];
    
    //创建滤镜
    CIFilter *filter = [CIFilter filterWithName:@"CIColorMonochrome"];
    
    //已有的值不变，其他的设为默认值
    [filter setDefaults];
    
    // 设置输入图像
    [filter setValue:ciImage forKey:@"inputImage"];
    // 获取输出图像
    CIImage * outputImg = [filter valueForKey:@"outputImage"];
    
    // 创建CIContex上下文对象
    CIContext * context = [CIContext contextWithOptions:nil];
    CGImageRef cgImg = [context createCGImage:outputImg fromRect:outputImg.extent];
    UIImage *resultImg = [UIImage imageWithCGImage:cgImg];
    CGImageRelease(cgImg);
    
    return resultImg;
}

- (UIImage *)grayImage{
    int bitmapInfo = kCGImageAlphaNone;
    int width = self.size.width;
    int height = self.size.height;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGContextRef context = CGBitmapContextCreate (nil,width,height,8,0,colorSpace,bitmapInfo);
    CGColorSpaceRelease(colorSpace);
    if (context == NULL) {
        return nil;
    }
    CGContextDrawImage(context,CGRectMake(0, 0, width, height), self.CGImage);
    UIImage *grayImage = [UIImage imageWithCGImage:CGBitmapContextCreateImage(context)];
    CGContextRelease(context);
    return grayImage;
}

@end
